<template>
  <div id="liveDPlayer" @dblclick="fullScreen"></div>
</template>

<script>
import Flv from "flv.js";
import DPlayer from "dplayer";

export default {
  props: {
    live_Options: Object
  },
  data() {
    return {
      isFullScreen: false,
      defaultQuality: 0,
      options: {},
      player: null,
      flvPlayer: null,
      isFist: false
    };
  },
  methods: {
    initDPlayer() {
      const that = this;
      this.options = {
        container: document.getElementById("liveDPlayer"),
        autoplay: true,
        screenshot: true,
        hotkey: false,
        live: true,
        volume: 0,
        video: {
          url: this.live_Options.play_url,
          type: "customFlv",
          customType: {
            customFlv: (video, player) => {
              this.flvPlayer = Flv.createPlayer(
                {
                  type: "flv",
                  url: video.src
                },
                {
                  isLive: true,
                  lazyLoad: true
                }
              );
              this.flvPlayer.attachMediaElement(video);
              this.flvPlayer.load();
            }
          }
        }
      };
      this.player = new DPlayer(this.options);

      this.player.on("play", () => {
        if (that.isFist) {
          // 重新实例化播放器
          that.playLive();
          that.isFist = false;
        }
      });
      this.player.on("pause", () => {
        that.isFist = true;
      });
    },
    playLive() {
      // 先销毁再重新加载
      if (this.flvPlayer) {
        this.flvPlayer.destroy();
        this.player.destroy();
      }
      this.initDPlayer();
    },
    fullScreen() {
      if (this.isFullScreen) {
        this.player.fullScreen.cancel("browser");
        this.isFullScreen = false;
      } else {
        this.player.fullScreen.request("browser");
        this.isFullScreen = true;
      }
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initDPlayer(this.live_Options);
    });
  },
  beforeDestroy() {
    this.flvPlayer.destroy();
    this.player.destroy();
  }
};
</script>
<style scoped>
#liveDPlayer {
  height: 100% !important;
  width: 100% !important;
}
</style>
